/**
 *
 * Copyright (c) 2009-2012 Envision Mobile Ltd. All rights reserved.
 *
 * Other software and company names mentioned herein or used for developing
 * and/or running the Envision Mobile Ltd's software may be trademarks or trade
 * names of their respective owners.
 *
 * Everything in the source code herein is owned by Envision Mobile Ltd.
 * The recipient of this source code hereby acknowledges and agrees that such
 * information is proprietary to Envision Mobile Ltd. and shall not be used, 
 * disclosed, duplicated, and/or reversed engineered except in accordance
 * with the express written authorization of Envision Mobile Ltd.
 *
 * Module: Utility.java
 * Project: RayOfLight
 *
 * Description:
 *
 *
 * Developer:   10107896
 * Date:        2012-08-13
 * Version:		1.0
 *
 *
 */
package org;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import database.DatabaseHelper;

import GameTools.ydPoint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;

public class Utility {

	public void initSQLDatabase(SQLiteDatabase db) {

	}

	public static SQLiteDatabase getDatabaseInstance(Activity act)
			throws SQLException, IOException {

		if (Globals.sqlDB == null) {
			// Initialize DB
			DatabaseHelper myDbHelper = DatabaseHelper.getInstance(act
					.getApplicationContext().getApplicationContext());

			try {
				Globals.sqlDB = myDbHelper.openDataBase();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		return Globals.sqlDB;
	}

	public static byte[] bitmaptoByteArray(Bitmap bmp) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
		byte[] byteArray = stream.toByteArray();
		return byteArray;
	}

	public static Drawable byteArrayToDrawable(
			byte[] byteArrayToBeCOnvertedIntoBitMap) {
		try {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inTempStorage = new byte[16 * 1024];
			options.inPurgeable = true;

			Bitmap bitMapImage = BitmapFactory.decodeByteArray(
					byteArrayToBeCOnvertedIntoBitMap, 0,
					byteArrayToBeCOnvertedIntoBitMap.length, options);

			Drawable drawable = scaleBitmapDrawable(new BitmapDrawable(
					bitMapImage));

			return drawable;
		} catch (Exception ex) {
			return null;
		}
	}

	public static Drawable byteArrayToDrawableForGallery(
			byte[] byteArrayToBeCOnvertedIntoBitMap) {
		try {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inTempStorage = new byte[16 * 1024];

			Bitmap bitMapImage = BitmapFactory.decodeByteArray(
					byteArrayToBeCOnvertedIntoBitMap, 0,
					byteArrayToBeCOnvertedIntoBitMap.length, options);

			Drawable drawable = new BitmapDrawable(bitMapImage);

			return drawable;
		} catch (Exception ex) {
			return null;
		}
	}

	public static Drawable scaleBitmapDrawable(BitmapDrawable drawable) {

		// WindowManager wm = (WindowManager)
		// ctx.getSystemService(Context.WINDOW_SERVICE);
		// Display display = wm.getDefaultDisplay();
		// Display display = getWindowManager().getDefaultDisplay();
		// Display display = ((WindowManager)
		// getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		int screenWidth = 320; // display.getWidth();
		int screenHeight = 480; // display.getHeight();

		int width = drawable.getBitmap().getWidth();
		int height = drawable.getBitmap().getHeight();

		float widthScale = 20.25f;
		float heightScale = 20.25f;

		/*
		 * if (width > screenWidth / 2.5f) { widthScale = 1.0f * screenWidth /
		 * width / 2.5f; }
		 * 
		 * if (height > screenHeight / 6.0f) { heightScale = 1.0f * screenHeight
		 * / 6.0f / height; }
		 */

		widthScale = Math.min(widthScale, heightScale);

		Bitmap bm = ((BitmapDrawable) drawable).getBitmap();
		return (new BitmapDrawable(scale(bm, 5, 5)));
	}

	public static Bitmap scale(Bitmap bm, double widthScale, double heightScale) {
		return Bitmap.createScaledBitmap(bm,
				(int) (bm.getWidth() * widthScale),
				(int) (bm.getHeight() * heightScale), false);
	}

	/**
	 * 
	 * @param activity
	 * @param message
	 * @param title
	 * @param positiveText
	 * @param negativeText
	 * @param intent
	 */
	public static void callConfirmationDialog(final Activity activity,
			final String message, final String title,
			final String positiveText, final String negativeText,
			final Intent intent) {
		// prepare the alert box
		final AlertDialog.Builder alertbox = new AlertDialog.Builder(activity);

		// set the message to display
		alertbox.setMessage(message);
		alertbox.setTitle(title);

		// add a neutral button to the alert box and assign a click listener
		alertbox.setPositiveButton(positiveText,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						if (intent != null) {
							activity.startActivity(intent);
						}
					}
				});

		// add a neutral button to the alert box and assign a click listener
		alertbox.setNegativeButton(negativeText,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});

		alertbox.show();
	}

	public static HashMap<Integer, Drawable> drawableCache;

	public static Drawable getDrawable(Context context, int resID,
			boolean isScaled) {

		if (drawableCache == null)
			drawableCache = new HashMap<Integer, Drawable>();

		Drawable drawable = null;
		if (drawableCache.containsKey(Integer.valueOf(resID))) {
			System.out.println("old");
			drawable = (Drawable) drawableCache.get(Integer.valueOf(resID));
		}

		if (drawable == null) {
			drawable = context.getResources().getDrawable(resID);
			if (drawable instanceof BitmapDrawable) {

				if (isScaled)
					drawable = scaleBitmapDrawable((BitmapDrawable) drawable);
			}
			if (drawable != null) {
				System.out.println("new");
				drawableCache.put(Integer.valueOf(resID), drawable);
			}
		}

		return drawable;
	}

	public static Path pointsToPath(ArrayList<ydPoint> points) {
		Path p = new Path();
		ydPoint point;
		for (int i = 0; i < points.size(); i++) {
			point = points.get(i);
			if (i == 0) {
				p.moveTo(point.x, point.y);
			} else {
				p.lineTo(point.x, point.y);
			}
		}
		return p;
	}

	public static JSONObject arrayListToJSONARRAY(ArrayList<ydPoint> points) {

		JSONObject obj = new JSONObject();
		for (int i = 0; i < points.size(); i++) {
			try {
				obj.put(i + "", points.get(i).toString());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Log.d("JSON_Recording", obj.toString());
		return obj;
	}

	public static Object pathToJSONARRAY(Path path) {

		int detail = 1000;

		JSONObject obj = new JSONObject();
		PathMeasure pm = new PathMeasure(path, false);
		// coordinates will be here
		float aCoordinates[] = { 0f, 0f };

		for (int i = 0; i < detail; i++) {
			pm.getPosTan(pm.getLength() * i / detail, aCoordinates, null);
			try {
				obj.put(i + "", aCoordinates[0] + " " + aCoordinates[1] + "");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return obj;
	}

	public static ArrayList<ydPoint> pathToArrayList(Path path) {
		int detail = 1000;

		ArrayList<ydPoint> points = new ArrayList<ydPoint>();
		PathMeasure pm = new PathMeasure(path, false);
		// coordinates will be here
		float aCoordinates[] = { 0f, 0f };

		for (int i = 0; i < detail; i++) {
			pm.getPosTan(pm.getLength() * i / detail, aCoordinates, null);
			points.add(new ydPoint(aCoordinates[0], aCoordinates[1]));

		}

		return points;
	}

	public static Bitmap ViewToBitmap(View v){
		
		Bitmap viewCapture = null;

		v.setDrawingCacheEnabled(true);

		viewCapture = Bitmap.createBitmap(v.getDrawingCache());

		v.setDrawingCacheEnabled(false);
		return viewCapture;
	}
	
	public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

		int width = bm.getWidth();

		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;

		float scaleHeight = ((float) newHeight) / height;

		// create a matrix for the manipulation

		Matrix matrix = new Matrix();

		// resize the bit map
		    matrix.postScale(scaleWidth, scaleHeight);   
		// recreate the new Bitmap

		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

		return resizedBitmap;

		}
}
